<template>
    <el-container class="related_partys_container">
        <vAside ref="aside" :options="asideOptions"
                :treeOptions="treeOptions"
                :treeData="treeData"
                @event="handleAsideEvent">
            <template slot="button">
                <i class="ml5 el-icon-circle-plus-outline"
                   v-permission="'save_base_related_party_type'"
                   @click="openTypeDialog(null, 'add')"/>
                <el-tooltip class="item" effect="dark"
                            content="全部分组" placement="top">
                    <i class="ml10 fa fa-list-ul"
                       :style="treeData.length && !treeNodeKey.sid ? 'color:#409EFf' : ''"
                       @click="getAllList()"/>
                </el-tooltip>
            </template>
        </vAside>
        <el-main>
            <el-card class="box-card">
                <header-template slot="header" ref="header"
                                 :table-ref="tableOptions.ref"
                                 :toolbar_buttons="toolbar_buttons"
                                 :searchForm="searchForm" title="模糊搜索编码、名称、简称、地址、电话、联系信息、身份证、信用代码"
                                 @event="handleEvent">
                    <template slot="right_search">
                        <el-form-item label="单位类型" style="margin-top: 4px; margin-bottom: 4px;">
                            <el-select v-model="searchForm.rec_type_list" placeholder="请选择"
                                       @change="getList(true)" class="w100" multiple
                                       style="margin-right: 5px;" clearable>
                                <el-option v-for="(item, index) in recTypeList"
                                           :key="index" :label="item.label" :value="item.value"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="合作状态" style="margin-top: 4px; margin-bottom: 4px;">
                            <el-select v-model="searchForm.state" placeholder="请选择"
                                       @change="getList(true)" class="w100"
                                       style="margin-right: 5px;" clearable>
                                <el-option v-for="(item, index) in stateList"
                                           :key="index" :label="item.label" :value="item.value"/>
                            </el-select>
                        </el-form-item>
                    </template>
                </header-template>
                <vxe-table-template :data="dataList" :options.sync="tableOptions"
                                    @event="handleTableEvent"/>
            </el-card>
        </el-main>
        <ImportExcel ref="commonImportExcelDialog" @postImport="handleImportData"/>

        <component-dialog dialog-drag :options="componentDialogOption" @event="handleDialogEvent"/>
    </el-container>
</template>

<script>
import baseRelatedPartyApi from "@common/api/base/baseRelatedPartyApi";
import ImportExcel from '@common/components/import/excel';
import poiApi from "@common/api/poiApi";
import TypeForm from "../dialog/components/TypeForm";
import ClientForm from "../dialog/related-party/ClientForm";
import UserClientForm from "../dialog/related-party/UserClientForm";
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "baseRelatedPartys",
    components: {ImportExcel},
    data() {
        let $this = this;
        return {
            isShrink: true,
            toolbar_buttons: [
                {
                    id: "refresh",
                    icon: "fa fa-refresh",
                    show: true,
                    method: () => {
                        $this.getList();
                    },
                },
                {
                    id: "add",
                    type: "primary",
                    icon: "fa fa-plus",
                    show: true,
                    permission: "save_base_related_party",
                    method: () => {
                        $this.openDialog(null, "add");
                    },
                },
                {
                    id: "edit",
                    type: "success",
                    icon: "fa fa-pencil",
                    show: true,
                    permission: "save_base_related_party",
                    method: () => {
                        $this.openDialog(null, "edit");
                    },
                },
                {
                    id: "del",
                    type: "danger",
                    icon: "fa fa-trash-o",
                    show: true,
                    permission: "del_base_related_party",
                    method: () => {
                        $this.confirmDel();
                    },
                },
                {
                    id: "import",
                    label: "导入",
                    class: "import",
                    icon: "el-icon-top",
                    show: true,
                    permission: "import_base_related_party",
                    method: () => {
                        $this.handleImportExcel();
                    },
                },
                {
                    id: "export",
                    label: "导出",
                    class: "export",
                    icon: "el-icon-download",
                    show: true,
                    permission: "export_base_related_party",
                    method: () => {
                        $this.handleExportExcel();
                    },
                },
            ], //左侧按钮
            toolbar_filter: [
                // { type: "text", field: "number", label: "编码" },
                // { type: "text", field: "name", label: "名称" },
            ], //精确筛选
            dataList: [],
            tableOptions: {
                ref: "related_partysTable",
                container: ".related_partys_container",
                multiSelect: true,
                columns: [
                    {
                        label: "单位类型",
                        prop: "rec_type",
                        align: "center",
                        formatter: (row) => {
                            if (row.rec_type === 1) {
                                return "客户";
                            } else if (row.rec_type === 2) {
                                return "供应商";
                            } else if (row.rec_type === 3) {
                                return "客户/供应商";
                            }
                            return '未知：' + row.rec_type;
                        },
                    },
                    {
                        label: "编码",
                        prop: "code",
                        align: "center",
                        width: 120,
                    },
                    {
                        label: "名称",
                        prop: "name",
                        align: "center",
                        width: 200,
                    },
                    {
                        label: "简称",
                        prop: "short_name",
                        align: "center",
                    },
                    {
                        label: "助记码",
                        prop: "search_code",
                        align: "center",
                    },
                    {
                        label: "电话",
                        prop: "phone",
                        align: "center",
                    },
                    {
                        label: "地址",
                        prop: "address",
                        align: "center",
                        width: 200,
                    },
                    {
                        label: "等级",
                        prop: "level_id",
                        align: "center",
                    },
                    {
                        label: "联系人",
                        prop: "linker_name",
                        align: "center",
                    },
                    {
                        label: "联系人电话",
                        prop: "linker_mobile",
                        align: "center",
                        width: 100,
                    },
                    {
                        label: "邮箱",
                        prop: "linker_email",
                        align: "center",
                        width: 100,
                    },
                    {
                        label: "合作状态",
                        prop: "state",
                        align: "center",
                        render(h, {row, column}) {
                            return h("el-switch", {
                                props: {
                                    value: row[column.prop] === 1,
                                },
                                on: {
                                    change(value) {
                                        $this.$set(row, column.prop, value === true ? 1 : 0);
                                        $this.saveRow(row);
                                    },
                                },
                            });
                        },
                    },
                ],
                operates: {
                    // width: 200,
                    fixed: "right",
                    list: [
                        {
                            id: "authorize",
                            icon: "el-icon-lx-people",
                            show: true,
                            tooltip: {
                                content: "授权",
                            },
                            permission: "auth_base_related_party",
                            method: (key, row, index) => {
                                $this.authorize(row, "authorize");
                            },
                        },
                        {
                            id: "copy",
                            icon: "el-icon-document-copy",
                            class: "cpbtn",
                            type: "primary",
                            show: true,
                            tooltip: {
                                content: "复制",
                            },
                            permission: "save_base_related_party",
                            method: (key, row, index) => {
                                $this.rowCopy(row, "copy");
                            },
                        },
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            show: true,
                            type: "success",
                            tooltip: {
                                content: "编辑",
                            },
                            permission: "save_base_related_party",
                            method: (key, row, index) => {
                                $this.openDialog(row, "edit");
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
            searchForm: {
                state: '',
            },
            stateList: [
                {label: '全部', value: ''},
                {label: '合作', value: 1},
                {label: '不合作', value: 0},
            ],
            recTypeList: [
                {label: '客户', value: 1},
                {label: '供应商', value: 2},
                {label: '客户/供应商', value: 3},
            ],
            selectionList: [],
            treeOptions: {
                ref: "$checkTree",
                highlightCurrent: true,
                defaultExpandAll: true,
                expandOnClickNode: false,
                props: {
                    label: "name",
                },
                // 右侧按钮
                buttons: [
                    {
                        icon: "el-icon-circle-plus-outline",
                        permission: "save_base_related_party_type",
                        filter(data) {
                            return data.sid !== '-1';
                        },
                        method: (data, $event) => {
                            $this.openTypeDialog(data, "add");
                        },
                    },
                    {
                        icon: "fa fa-pencil",
                        permission: "save_base_related_party_type",
                        filter(data) {
                            return data.sid !== '-1';
                        },
                        method: (data, $event) => {
                            $this.openTypeDialog(data, "edit");
                        },
                    },
                    {
                        icon: "fa fa-trash-o",
                        permission: "del_base_related_party_type",
                        filter(data) {
                            return data.sid !== '-1';
                        },
                        method: (data, $event) => {
                            $this.handleClientTypeConfirm(data);
                        },
                    },
                ],
            },
            initTreeList: [],
            treeData: [],
            asideOptions: {
                width: "300px",
                title: "往来单位分组",
            },
            treeNodeKey: {}, //当前选中树节点
        };
    },
    mounted() {
        this.initTreeData();
    },
    methods: {
        // 获取分组树的数据
        initTreeData() {
            let $this = this;
            let queryData = {};
            baseRelatedPartyApi.findBaseRelatedPartyTypeTree(queryData, (result) => {
                $this.initTreeList = result.data || [];
                $this.treeData = result.data || [];
                $this.getList();
            });
        },
        openTypeDialog(row, type) {
            const _this = this;
            let title = type === 'add' ? '创建分组' : '编辑分组';
            if (type === 'add') {
                row = {
                    parent_sid: row ? row.sid : 'root',
                    rec_type: 0,
                };
            }
            _this.openComponentDialog({
                width: '400px',
                title,
                component: TypeForm,
                propsData: {
                    api: _this.$api.API_SaveBaseRelatedParty,
                    row,
                },
                callback() {
                    _this.initTreeData();
                },
            });
        },
        // 全部按钮点击事件
        getAllList() {
            let $this = this;
            $this.treeNodeKey = {};
            $this.$checkTree && $this.$checkTree.setCurrentKey(null);
            $this.tableOptions.pagination.pageIndex = 1;
            $this.getList();
        },
        // 分组删除确认
        handleClientTypeConfirm(data) {
            let id = data.id;
            let $this = this;
            if (data.children && data.children.length) {
                return $this.$message.warning("存在下级分组，请先删除下级分组");
            }
            $this.$confirm("是否确认删除分组，分组下的数据也会删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                baseRelatedPartyApi.deleteRelatedPartyType({id}, () => {
                    if (id === $this.treeNodeKey.id) {
                        $this.treeNodeKey = {};
                    }
                    $this.initTreeData();
                    $this.$message.success("删除成功");
                });
            }).catch(() => {
            });
        },
        // 接收当前点击分组
        handleAsideEvent(event) {
            let $this = this;
            if (event.type === "nodeClick") {
                $this.treeNodeKey = event.data;
                $this.getList();
            }
        },
        // 接收搜索条件
        handleEvent(event) {
            let $this = this;
            console.log(event);
            $this.searchForm = $.extend({}, $this.searchForm, event.searchForm);
            if (event.type === "search") {
                $this.getList(true);
            } else if (event.type === "refresh") {
                $this.getList(true);
            }
        },
        // 行点击事件，并修改值
        saveRow(row) {
            let $this = this;
            baseRelatedPartyApi.saveBaseRelatedParty(row, (result) => {
                $this.$message.success("保存成功！");
            });
        },
        rowCopy(row) {
            let $this = this;
            let arr = [];
            $this.tableOptions.columns.forEach((item) => {
                if (item.prop !== "state") {
                    arr.push(item.label+":");
                    arr.push(row[item.prop]);
                }
            });
            let Str = arr.join(" ");
            if ($this.$XEUtils.stringCopy(Str)) {
                $this.$message.success("复制成功！");
            } else {
                $this.$message.success("复制失败");
            }
        },
        // 获取往来单位列表
        getList(search) {
            let $this = this;
            $this.dataList = [];
            if (search) {
                $this.tableOptions = $this.resetTablePagination($this.tableOptions);
            }
            let queryData = $this.getQueryParams($this.tableOptions, $this.searchForm);
            if ($this.treeNodeKey.sid) {
                queryData.parent_sid = $this.treeNodeKey.sid;
            } else {
                delete queryData.parent_sid;
            }
            queryData.is_group = 0;
            baseRelatedPartyApi.findBaseRelatedPartys(queryData, result => {
                $this.dataList = result.data || [];
                $this.tableOptions = $this.setTableTotal($this.tableOptions, result);
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        authorize(row, type) {
            const _this = this;
            _this.openComponentDialog({
                width: '1000px',
                title: '授权',
                component: UserClientForm,
                propsData: {
                    row,
                },
            });
        },
        openDialog(row, type) {
            const _this = this;
            let title = type === "add" ? "创建" : "编辑";
            if (!row) {
                if (type === 'add') {
                    row = {};
                    if (_this.treeNodeKey && _this.treeNodeKey.sid) {
                        row = {parent_sid: _this.treeNodeKey.sid};
                    }
                }
                if (type === 'edit') {
                    if (!_this.checkSelection(_this.selectionList)) {
                        return;
                    }
                    row = $.extend({}, _this.selectionList[0]);
                }
            }
            _this.openComponentDialog({
                width: '60%',
                title,
                component: ClientForm,
                propsData: {
                    row,
                    treeList: _this.initTreeList,
                },
                noCloseBtn: true,
                btns: [],
            });
        },
        handleDialogEvent(event) {
            if (event.type === 'refresh') {
                this.getList();
            }
        },
        // 确认删除用户
        confirmDel(row) {
            let $this = this;
            let ids = [];
            if (row) {
                ids.push(row.sid);
            } else {
                if (!$this.checkSelection($this.selectionList, true)) {
                    return;
                }
                ids = $this.selectionList.map(item => item.sid);
            }
            $this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                baseRelatedPartyApi.batchDeleteBaseRelatedParty({sids: ids}, () => {
                    $this.getList();
                    $this.$message.success("删除成功");
                });
            })
                .catch(() => {
                });
        },
        handleExportExcel() {
            let queryData = $.extend({}, this.searchForm);
            queryData.is_group = 0;
            //Excel通用导出
            let title_field = [
                {name: "序号", key: "_index", width: 10},
                {name: "单位类型", key: "rec_type", width: 20},
                {name: "编码", key: "code", width: 20},
                {name: "名称", key: "name", width: 20},
                {name: "简称", key: "short_name", width: 20},
                {name: "助记码", key: "search_code", width: 20},
                {name: "电话", key: "phone", width: 20},
                {name: "地址", key: "address", width: 20},
                {name: "等级", key: "level_id", width: 20},
                {name: "联系人", key: "linker_name", width: 20},
                {name: "联系电话", key: "linker_mobile", width: 20},
                {name: "联系邮箱", key: "linker_email", width: 20},
                {name: "合作状态", key: "state"},
            ];
            let convert = {
                state: [
                    {name: "合作", value: 1},
                    {name: "不合作", value: 0},
                ],
                rec_type: [
                    {name: "客户", value: 1},
                    {name: "供应商", value: 2},
                    {name: "客户/供应商", value: 3},
                ],
            };
            poiApi.exportExcel(
                title_field,
                this.$api.API_FindBaseRelatedPartys,
                queryData,
                "往来单位清单",
                convert
            );
        },
        handleImportExcel() {
            let _this = this;
            if (_this.$refs['commonImportExcelDialog']) {
                _this.$refs['commonImportExcelDialog'].showDialog({
                    visible: true,
                    title: '导入',
                    configFile: 'RelatedParty.xml',
                    downloadFile: '往来单位表.xlsx',
                });
            }
        },
        handleImportData(data) {
            let _this = this;
            baseRelatedPartyApi.importBaseRelatedParty({list: data.list}, () => {
                _this.$message.success("导入成功");
                _this.$refs['commonImportExcelDialog'].closeDialog();
                _this.getList();
            }, (res) => {
                _this.$refs['commonImportExcelDialog'].enableImportBtn();
                _this.$refs['commonImportExcelDialog'].showErrorMsg(res.message);
                _this.$message.error(res.message);
            });
        },
    },
};
</script>

<style lang="less" type="stylesheet/less" scoped>
.related_partys_container {
    height: 100%;

    .buttons {
        margin: 0 0 10px 0;
    }

    /deep/ .import {
        background-color: #67C23A;
        border-color: #67C23A;
        color: #fff;
    }

    /deep/ .export {
        background-color: #E6A23C;
        border-color: #E6A23C;
        color: #fff;
    }
}

</style>
